/*
 * Copyright 2011 Katsunori Koyanagi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	import mx.collections.ArrayCollection;
	import mx.events.CollectionEvent;
	import mx.events.CollectionEventKind;

	public class TestTargetData extends ArrayCollection
	{

		private var _file:File;

		public function TestTargetData()
		{
			_file = File.applicationDirectory.resolvePath(".");
			_file.canonicalize();
			_file = new File(_file.nativePath + "/../testdata/test.xml");

			load();
		}

		public function save():void
		{
			var xml:XML = <targets/>;
			for each (var target:TestTarget in this)
			{
				xml.target += <target url={target.url} enabled={target.enabled}/>;
			}


			var stream:FileStream = new FileStream();
			stream.open(_file, FileMode.WRITE);
			stream.writeUTFBytes(xml.toXMLString());
			stream.close();
		}

		private function load():void
		{
			var stream:FileStream = new FileStream();
			stream.open(_file, FileMode.READ);
			var bytes:ByteArray = new ByteArray();
			stream.readBytes(bytes);
			stream.close();

			var xml:XML = null;
			try
			{
				xml = new XML(bytes);
				for each (var node:XML in xml.*)
				{
					var target:TestTarget = new TestTarget();
					target.url = node.@url;
					target.enabled = node.@enabled == "true";
					addItem(target);
				}
			}
			catch (e:Error)
			{
				save();
			}
		}
	}
}
